<?php


namespace App\Job;


use App\Config\QueueConfig;
use App\Http\Library\Queue;
use App\Http\Model\Job\ClassNettingModel;

class ClassNettingJob
{

    /**
     * 班级-当日 班级&账户 轧差净额
     *
     * @param array $data
     *
     * @return int
     * @throws \Exception
     */
    public static function main(array $data)
    {
        log_arr([
            '[班级&账户当日轧差净额计算]',
            'data' => serialize($data),
        ], 'pfs');
        if (!empty($data['sleep'])) {
            sleep($data['sleep']);
            unset($data['sleep']);
        }
        /*查询需要计算的轧差日期*/
        $createDate = ClassNettingModel::createDate($data);
        $id = empty($data['id']) ? 0 : $data['id'];
        /*需要进行轧差计算的数据*/
        $list = ClassNettingModel::list($data, $id, $createDate);
        /*当日待推送所有班级汇总缴费课程金额&当日待推送所有班级汇总退费课程金额*/
        $accountSum = ClassNettingModel::accountSum($data, $createDate);
        /*
         * 当日账户轧差净额
         * 当日账户轧差净额 = 当日待推送所有班级汇总缴费课程金额 - 当日缴费手续费 - 当日待推送所有班级汇总退费课程金额 + 当日退费手续费
         * */
        $accountNetting = bcsub($accountSum['pay_amt_sum'], $accountSum['refund_amt_sum']);
        if (empty($list)) {
            //$accountNetting = -1;
            /*备份金退费借回   机构端 -> 招行*/
            self::withdrawProvision($data, $accountNetting, $createDate);
            return 0;
        }
        /*计算本次要计算的结果*/
        foreach ($list as $val) {
            /*更新ID迁移量*/
            $data['id'] = $val->id;
            /*
             * 当日班级轧差净额
             * 当日班级轧差净额 = 当日缴费课程金额 - 当日缴费手续费 - 当日退费课程金额 + 当日退费手续费
             * */
            $classNetting = bcsub($val->pay_amt, $val->refund_amt);
            /*班级-当日 班级&账户 轧差净额:更新表数据*/
            ClassNettingModel::save([
                'class_netting'   => $classNetting,
                'account_netting' => $accountNetting,
            ], $val->id);
        }
        /*如果没有计算完,就继续计算*/
        Queue::rpush($data);
    }


    /**
     * 触发任务:备份金退费借回   机构端 -> 招行
     *
     * @param $data
     * @param $accountNetting
     * @param $createDate
     *
     * @throws \Exception
     */
    private static function withdrawProvision($data, $accountNetting, $createDate)
    {
        if (bccomp($accountNetting, 0) === -1) {
            Queue::rpush([
                'pfs_dw_id'       => $data['pfs_dw_id'],
                'account_netting' => $accountNetting,
                'create_date'     => $createDate,
                'origin'          => empty($data['origin']) ? '' : $data['origin'],
            ], QueueConfig::PFS_HEAD_WITHDRAWPROVISION);
        }
    }

}





/**
 * ClassNettingJob.php
 *
 * 说明:
 *
 * 修改历史
 * ----------------------------------------
 * 2021/6/8 19:41:00   操作:创建
 **/
